import {
  app, BrowserWindow, protocol, Menu,
} from 'electron';
import path from 'path';
import { IPC } from './ipc/ipc';

Menu.setApplicationMenu(null);

async function createWindow(): Promise<BrowserWindow> {
  const win = new BrowserWindow({
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: true,
      preload: path.join(__dirname, '../electron-preload/index.js'),
      webSecurity: false,
    },
    frame: true, // 标题栏和边框一并隐藏
    width: 1920,
    height: 1080,
  });
  if (app.isPackaged) {
    win.loadFile(path.join(__dirname, '../index.html'));
  } else {
    // 🚧 Use ['ENV_NAME'] avoid vite:define plugin
    const { env } = process;
    const url = `http://${env.VITE_DEV_SERVER_HOST}:${env.VITE_DEV_SERVER_PORT}`;

    win.loadURL(url);
  }

  win.webContents.openDevTools();

  win.on('resize', () => {
    win.webContents.send('resizeEvent');
  });

  // eslint-disable-next-line no-new
  new IPC(win);

  return win;
}

let mainWindow: BrowserWindow;

app.whenReady().then(async () => {
  mainWindow = await createWindow();

  protocol.registerFileProtocol('local', (request, callback) => {
    const pathname = request.url.substring(9);
    const localPath = path.normalize(decodeURIComponent(pathname));
    callback(localPath);
  });

  app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// eslint-disable-next-line no-lone-blocks
{
  // 注册 url 打开客户端协议
  if (process.defaultApp) {
    if (process.argv.length >= 2) {
      app.setAsDefaultProtocolClient('iBiz', process.execPath, [path.resolve(process.argv[1])]);
    }
  } else {
    app.setAsDefaultProtocolClient('iBiz');
  }

  app.on('second-instance', (event, commandLine, workingDirectory) => {
    if (mainWindow) {
      if (mainWindow) {
        // 如果被最小化就恢复，否则激活主窗口
        if (mainWindow.isMinimized()) mainWindow.restore();
        mainWindow.focus();
      }
    }
  });
}
